'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useEffect, useState } from 'react'
import { Clapperboard } from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Button } from "@/components/ui/button"
import { useRouter } from 'next/navigation'

const navigation = [
  { href: '/', label: '首页' },
  { href: '/topics', label: '项目' },
  { href: '/progress', label: '进度' },
  { href: '/music', label: '音乐' },
  { href: '/read', label: '提词器' },
  { href: '/cover', label: '封面' },
]

export default function Header() {
  const pathname = usePathname()
  const router = useRouter()
  const [user, setUser] = useState<{ email?: string } | null>(null)

  const handleLogout = () => {
    localStorage.clear()
    setUser(null)
    router.push('/')
  }

  useEffect(() => {
    const fetchUser = async () => {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch('/api/auth/me', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            if (response.ok) {
                const userData = await response.json();
                setUser(userData);
            } else {
                console.error('Failed to fetch user data');
            }
        } catch (error) {
            console.error('Error fetching user:', error);
        }
    };

    fetchUser();
}, []);

  return (
    <header className="bg-white/80 backdrop-blur-md sticky top-0 z-50">
      <nav className="mx-auto container px-8" aria-label="Top">
        <div className="flex w-full items-center justify-between border-b border-gray-200/50 py-4 md:py-6">
          <div className="flex items-center space-x-6 md:space-x-8">
            <Link href="/" className="flex items-center space-x-2">
              <span className="sr-only">VideoFlow</span>
              <Clapperboard className='w-6 h-6 text-indigo-900'/>
              <span className="text-xl font-bold text-gray-900">VideoFlow</span>
            </Link>
            <div className="flex items-center space-x-2 md:space-x-4">
              {navigation.map((link) => (
                <Link
                  key={link.href}
                  href={link.href}
                  className={`text-sm font-medium px-3 py-2 rounded-lg transition-colors duration-200
                    ${pathname === link.href
                      ? 'text-gray-900 bg-gray-100/50'
                      : 'text-gray-700 hover:text-gray-900 hover:bg-gray-100/50'
                    }`}
                >
                  {link.label}
                </Link>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-4">
            {user ? (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="flex items-center gap-2">
                    <span>{user.email}</span>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-48">
                  <DropdownMenuLabel>账户</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={handleLogout}>
                    退出登录
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            ) : (
              <>
                <Button variant="outline" onClick={() => router.push('/login')}>
                  登录
                </Button>
                <Button onClick={() => router.push('/register')}>
                  注册
                </Button>
              </>
            )}
          </div>
        </div>
      </nav>
    </header>
  )
}
